package com.example.screenshot_service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.PixelFormat
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowManager
import android.widget.ImageView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import com.example.patchouli_knowledge.MainActivity
import com.example.patchouli_knowledge.R
import java.util.concurrent.atomic.AtomicBoolean

/**
 * 悬浮窗服务类，用于检测长按并显示悬浮球
 */
class FloatingWindowService : Service() {
    private val TAG = "FloatingWindowService"
    private lateinit var windowManager: WindowManager
    private lateinit var floatingView: View
    private lateinit var floatingBallView: View
    private var isLongPressDetected = AtomicBoolean(false)
    private var longPressHandler: Handler? = null
    private var longPressRunnable: Runnable? = null
    private val LONG_PRESS_TIMEOUT = ViewConfiguration.getLongPressTimeout() + 200L // 系统长按时间加200毫秒
    private var touchDownX = 0f
    private var touchDownY = 0f
    private val TOUCH_SLOP = 10 // 触摸位移容差
    
    companion object {
        private const val NOTIFICATION_ID = 1001
        private const val CHANNEL_ID = "FloatingWindowChannel"
        private var isServiceRunning = false
        
        fun isRunning(): Boolean {
            return isServiceRunning
        }
    }

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "悬浮窗服务已创建")
        windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        
        // 创建消息通知渠道
        createNotificationChannel()
        
        // 启动前台服务，提高服务优先级，降低系统回收服务的可能性
        startForeground(NOTIFICATION_ID, createNotification())
        
        // 初始化长按检测处理程序
        longPressHandler = Handler(Looper.getMainLooper())
        
        // 初始化悬浮窗视图（透明的，覆盖整个屏幕，用于检测长按）
        setupFloatingView()
        
        // 初始化悬浮球视图（点击后截图）
        setupFloatingBallView()
        
        isServiceRunning = true
    }

    /**
     * 创建通知渠道（Android 8.0及以上需要）
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "悬浮窗服务"
            val description = "提供长按检测和屏幕截图功能"
            val importance = NotificationManager.IMPORTANCE_LOW
            val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
                this.description = description
            }
            
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    /**
     * 创建前台服务通知
     */
    private fun createNotification(): Notification {
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 从Android 6.0开始支持FLAG_IMMUTABLE
            PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        } else {
            PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        }

        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("知拾")
            .setContentText("正在后台运行，长按屏幕可以截图")
            .setSmallIcon(R.mipmap.launcher_icon)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .build()
    }

    /**
     * 设置悬浮窗视图，用于检测长按
     */
    private fun setupFloatingView() {
        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        
        // 创建一个透明视图覆盖全屏
        floatingView = View(this).apply {
            // 设置为完全透明
            setBackgroundColor(android.graphics.Color.TRANSPARENT)
        }
        
        // 设置悬浮窗参数
        val params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            else 
                WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    or WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
                    or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
            PixelFormat.TRANSLUCENT
        )
        
        // 设置触摸监听
        floatingView.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    // 记录按下的位置
                    touchDownX = event.rawX
                    touchDownY = event.rawY
                    
                    // 如果之前有未完成的长按任务，先移除
                    longPressRunnable?.let { longPressHandler?.removeCallbacks(it) }
                    
                    // 重置长按状态
                    isLongPressDetected.set(false)
                    
                    // 创建长按任务
                    longPressRunnable = Runnable {
                        if (!isLongPressDetected.getAndSet(true)) {
                            // 长按触发，显示悬浮球
                            showFloatingBall(event.rawX, event.rawY)
                        }
                    }
                    
                    // 启动长按定时器
                    longPressHandler?.postDelayed(longPressRunnable!!, LONG_PRESS_TIMEOUT)
                }
                MotionEvent.ACTION_MOVE -> {
                    // 如果移动距离过大，取消长按
                    val deltaX = Math.abs(event.rawX - touchDownX)
                    val deltaY = Math.abs(event.rawY - touchDownY)
                    if (deltaX > TOUCH_SLOP || deltaY > TOUCH_SLOP) {
                        longPressRunnable?.let { longPressHandler?.removeCallbacks(it) }
                    }
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    // 取消长按任务
                    longPressRunnable?.let { longPressHandler?.removeCallbacks(it) }
                }
            }
            true
        }
        
        // 添加悬浮窗到窗口管理器
        try {
            windowManager.addView(floatingView, params)
        } catch (e: Exception) {
            Log.e(TAG, "添加悬浮窗失败: ${e.message}")
        }
    }

    /**
     * 设置悬浮球视图，显示logo并提供截图功能
     */
    private fun setupFloatingBallView() {
        // 创建悬浮球视图
        floatingBallView = LayoutInflater.from(this).inflate(R.layout.floating_ball_layout, null)
        
        // 设置悬浮球图标
        val imageView = floatingBallView.findViewById<ImageView>(R.id.floating_ball_icon)
        imageView.setImageResource(R.drawable.logo)
        
        // 设置点击监听，执行截图
        floatingBallView.setOnClickListener {
            // 隐藏悬浮球
            try {
                windowManager.removeView(floatingBallView)
            } catch (e: Exception) {
                Log.e(TAG, "移除悬浮球失败: ${e.message}")
            }
            
            // 延迟200毫秒后执行截图，给UI时间隐藏悬浮球
            Handler(Looper.getMainLooper()).postDelayed({
                takeScreenshot()
            }, 200)
        }
    }

    /**
     * 显示悬浮球在长按位置附近
     */
    private fun showFloatingBall(x: Float, y: Float) {
        // 设置悬浮球参数
        val size = resources.getDimensionPixelSize(R.dimen.floating_ball_size)
        val params = WindowManager.LayoutParams(
            size,
            size,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            else
                WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT
        )
        
        // 设置悬浮球位置，确保在屏幕内
        params.gravity = Gravity.START or Gravity.TOP
        params.x = (x - size / 2).toInt().coerceIn(0, windowManager.defaultDisplay.width - size)
        params.y = (y - size / 2).toInt().coerceIn(0, windowManager.defaultDisplay.height - size)
        
        // 添加悬浮球到窗口管理器
        try {
            // 如果已经添加过，先移除
            try {
                windowManager.removeView(floatingBallView)
            } catch (e: Exception) {
                // 忽略错误，可能是第一次添加
            }
            
            windowManager.addView(floatingBallView, params)
            
            // 显示提示
            Toast.makeText(this, "点击图标可截取屏幕", Toast.LENGTH_SHORT).show()
            
            // 5秒后自动隐藏悬浮球
            Handler(Looper.getMainLooper()).postDelayed({
                try {
                    windowManager.removeView(floatingBallView)
                } catch (e: Exception) {
                    // 忽略错误
                }
            }, 5000)
        } catch (e: Exception) {
            Log.e(TAG, "显示悬浮球失败: ${e.message}")
        }
    }

    /**
     * 执行屏幕截图
     */
    private fun takeScreenshot() {
        val screenshotService = ScreenshotService.getInstance()
        if (screenshotService != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 执行截图
            screenshotService.takeScreenshot { imagePath ->
                if (imagePath != null) {
                    // 截图成功
                    Handler(Looper.getMainLooper()).post {
                        Toast.makeText(this, "截图成功，已保存到相册", Toast.LENGTH_SHORT).show()
                    }
                    
                    // 保存到相册
                    try {
                        val file = java.io.File(imagePath)
                        if (file.exists()) {
                            // 通知图库更新
                            val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
                            val contentUri = android.net.Uri.fromFile(file)
                            mediaScanIntent.data = contentUri
                            sendBroadcast(mediaScanIntent)
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "保存截图到相册失败: ${e.message}")
                    }
                } else {
                    // 截图失败
                    Handler(Looper.getMainLooper()).post {
                        Toast.makeText(this, "截图失败", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        } else {
            Handler(Looper.getMainLooper()).post {
                Toast.makeText(this, "无障碍服务未启用，无法截图", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        // 移除悬浮窗和悬浮球
        try {
            windowManager.removeView(floatingView)
            windowManager.removeView(floatingBallView)
        } catch (e: Exception) {
            // 忽略错误
        }
        
        // 移除所有回调
        longPressHandler?.removeCallbacksAndMessages(null)
        
        isServiceRunning = false
        Log.d(TAG, "悬浮窗服务已销毁")
    }
} 